<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { message } from "ant-design-vue"

const activeTab = ref('1')
const dateRange = ref([dayjs().subtract(6, 'month'), dayjs()])

// 薪资表格列配置
const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '工号',
    dataIndex: 'employeeId',
    key: 'employeeId'
  },
  {
    title: '部门',
    dataIndex: 'department',
    key: 'department'
  },
  {
    title: '职位',
    dataIndex: 'position',
    key: 'position'
  },
  {
    title: '基本工资',
    dataIndex: 'baseSalary',
    key: 'baseSalary'
  },
  {
    title: '实发工资',
    dataIndex: 'actualSalary',
    key: 'actualSalary'
  },
  {
    title: '发放月份',
    dataIndex: 'month',
    key: 'month'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '操作',
    key: 'action',
    width: '180px'
  }
]

// 薪资数据
const salaryData = ref([
  {
    id: 1,
    name: '张三',
    employeeId: '1001',
    department: '技术部',
    position: '前端开发',
    baseSalary: '15000',
    actualSalary: '15800',
    month: '2023-09',
    status: 1,
    bonus: 800,
    allowance: 0,
    insurance: 1200,
    tax: 500,
    attendanceDays: 22,
    leaveDays: 1,
    overtimeHours: 8
  },
  {
    id: 2,
    name: '李四',
    employeeId: '1002',
    department: '技术部',
    position: '后端开发',
    baseSalary: '16000',
    actualSalary: '16800',
    month: '2023-09',
    status: 1,
    bonus: 800,
    allowance: 0,
    insurance: 1200,
    tax: 600,
    attendanceDays: 22,
    leaveDays: 0,
    overtimeHours: 5
  },
  {
    id: 3,
    name: '王五',
    employeeId: '1003',
    department: '产品部',
    position: '产品经理',
    baseSalary: '18000',
    actualSalary: '18500',
    month: '2023-09',
    status: 1,
    bonus: 500,
    allowance: 0,
    insurance: 1500,
    tax: 700,
    attendanceDays: 22,
    leaveDays: 0,
    overtimeHours: 3
  },
  {
    id: 4,
    name: '赵六',
    employeeId: '1004',
    department: '市场部',
    position: '市场专员',
    baseSalary: '12000',
    actualSalary: '12500',
    month: '2023-10',
    status: 2,
    bonus: 500,
    allowance: 0,
    insurance: 1000,
    tax: 400,
    attendanceDays: 20,
    leaveDays: 2,
    overtimeHours: 10
  },
  {
    id: 5,
    name: '钱七',
    employeeId: '1005',
    department: '财务部',
    position: '会计',
    baseSalary: '13000',
    actualSalary: '13500',
    month: '2023-10',
    status: 2,
    bonus: 500,
    allowance: 0,
    insurance: 1100,
    tax: 450,
    attendanceDays: 21,
    leaveDays: 1,
    overtimeHours: 2
  }
])

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 5
})

// 薪资模态框相关
const salaryModalVisible = ref(false)
const salaryFormState = ref({
  month: null,
  payDate: null,
  remark: ''
})

// 详情模态框相关
const detailModalVisible = ref(false)
const currentDetail = ref(null)

// 编辑模态框相关
const editModalVisible = ref(false)
const editFormState = ref({
  id: null,
  baseSalary: null,
  bonus: null,
  allowance: null,
  insurance: null,
  tax: null,
  remark: ''
})

// 查看详情
const viewDetail = (record) => {
  currentDetail.value = record
  detailModalVisible.value = true
}

// 编辑薪资
const editSalary = (record) => {
  editFormState.value = {
    id: record.id,
    baseSalary: record.baseSalary,
    bonus: record.bonus,
    allowance: record.allowance || 0,
    insurance: record.insurance,
    tax: record.tax,
    remark: ''
  }
  editModalVisible.value = true
}

// 提交薪资编辑
const handleEditSubmit = () => {
  const index = salaryData.value.findIndex(item => item.id === editFormState.value.id)
  if (index !== -1) {
    // 计算新的实发工资
    const actualSalary =
        Number(editFormState.value.baseSalary) +
        Number(editFormState.value.bonus) +
        Number(editFormState.value.allowance) -
        Number(editFormState.value.insurance) -
        Number(editFormState.value.tax)

    salaryData.value[index] = {
      ...salaryData.value[index],
      baseSalary: editFormState.value.baseSalary.toString(),
      bonus: editFormState.value.bonus,
      allowance: editFormState.value.allowance,
      insurance: editFormState.value.insurance,
      tax: editFormState.value.tax,
      actualSalary: actualSalary.toString()
    }

    message.success('薪资信息更新成功')
    editModalVisible.value = false
  }
}

// 显示发放薪资模态框
const showSalaryModal = () => {
  salaryModalVisible.value = true
}

// 提交薪资发放
const handleSalarySubmit = () => {
  console.log('提交薪资发放:', salaryFormState.value)
  salaryModalVisible.value = false
  message.success('薪资发放计划已创建')
}

// 取消薪资发放
const handleSalaryCancel = () => {
  salaryModalVisible.value = false
}

// 日期范围变化
const handleDateChange = (dates) => {
  console.log('日期范围变化:', dates)
  // 实际项目中应该根据日期范围重新获取数据
}

let myChart = null // 存储图表实例

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('salary-distribution-chart')

  // 确保DOM元素存在
  if (!chartDom) {
    return
  }

  // 如果已有图表实例，先销毁
  if (myChart) {
    myChart.dispose()
  }

  myChart = echarts.init(chartDom)

  // 从数据中计算各部门的平均薪资
  const departmentStats = {}
  salaryData.value.forEach(item => {
    if (!departmentStats[item.department]) {
      departmentStats[item.department] = {
        total: 0,
        count: 0
      }
    }
    departmentStats[item.department].total += Number(item.actualSalary)
    departmentStats[item.department].count++
  })

  const departments = Object.keys(departmentStats)
  const averageSalaries = departments.map(dept =>
      Math.round(departmentStats[dept].total / departmentStats[dept].count))

  // 按薪资从高到低排序
  const sortedData = departments
      .map((dept, index) => ({ dept, salary: averageSalaries[index] }))
      .sort((a, b) => b.salary - a.salary)

  const sortedDepartments = sortedData.map(item => item.dept)
  const sortedSalaries = sortedData.map(item => item.salary)

  const option = {
    title: {
      text: '各部门平均薪资对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>平均薪资: {c}元'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: sortedDepartments,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '平均薪资(元)',
      axisLine: {
        show: true
      },
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '平均薪资',
        type: 'bar',
        data: sortedSalaries,
        itemStyle: {
          color: function(params) {
            // 渐变色
            const colorList = [
              '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
              '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570'
            ]
            return colorList[params.dataIndex % colorList.length]
          },
          borderRadius: [4, 4, 0, 0],
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 5
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}元'
        },
        barWidth: '40%'
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ]
  }

  myChart.setOption(option)

  window.addEventListener('resize', handleResize)
}

// 处理窗口resize
const handleResize = () => {
  if (myChart) {
    myChart.resize()
  }
}

// 标签切换处理
const handleTabChange = (activeKey) => {
  // 当切换到"薪资统计"标签时初始化图表
  if (activeKey === '2') {
    // 使用nextTick确保DOM更新完成
    nextTick(() => {
      initChart()
    })
  }
}

// 组件卸载时清理
onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
  window.removeEventListener('resize', handleResize)
})

onMounted(() => {
  // 如果默认是"薪资统计"标签，初始化图表
  if (activeTab.value === '2') {
    nextTick(() => {
      initChart()
    })
  }
})
</script>

<template>
  <div class="salary-container">
    <a-card title="薪资管理">
      <template #extra>
        <a-range-picker
            v-model:value="dateRange"
            picker="month"
            @change="handleDateChange"
            style="width: 250px; margin-right: 10px"
        />
        <a-button type="primary" @click="showSalaryModal">发放薪资</a-button>
      </template>

      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <a-tab-pane key="1" tab="薪资记录">
          <a-table
              :columns="columns"
              :data-source="salaryData"
              :pagination="pagination"
              row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="record.status === 1 ? 'green' : 'orange'">
                  {{ record.status === 1 ? '已发放' : '待发放' }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewDetail(record)">详情</a-button>
                  <a-button size="small" @click="editSalary(record)" v-if="record.status === 2">编辑</a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="薪资统计">
          <div class="statistics-container">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-card title="平均薪资" :bordered="false">
                  <div class="stat-card">
                    <h2>¥15,800</h2>
                    <p>较上月 <span class="increase">↑5%</span></p>
                  </div>
                </a-card>
              </a-col>
              <a-col :span="8">
                <a-card title="最高薪资" :bordered="false">
                  <div class="stat-card">
                    <h2>¥28,500</h2>
                    <p>技术部</p>
                  </div>
                </a-card>
              </a-col>
              <a-col :span="8">
                <a-card title="最低薪资" :bordered="false">
                  <div class="stat-card">
                    <h2>¥8,200</h2>
                    <p>客服部</p>
                  </div>
                </a-card>
              </a-col>
            </a-row>

            <a-card title="部门薪资分布" style="margin-top: 16px;">
              <div id="salary-distribution-chart" style="height: 300px;"></div>
            </a-card>
          </div>
        </a-tab-pane>
      </a-tabs>

      <!-- 发放薪资模态框 -->
      <a-modal
          v-model:visible="salaryModalVisible"
          title="发放薪资"
          @ok="handleSalarySubmit"
          @cancel="handleSalaryCancel"
      >
        <a-form :model="salaryFormState" :label-col="{ span: 6 }">
          <a-form-item label="发放月份" required>
            <a-date-picker
                v-model:value="salaryFormState.month"
                picker="month"
                style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="发放日期" required>
            <a-date-picker
                v-model:value="salaryFormState.payDate"
                style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="备注">
            <a-textarea v-model:value="salaryFormState.remark" :rows="3" />
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 薪资详情模态框 -->
      <a-modal
          v-model:visible="detailModalVisible"
          title="薪资详情"
          width="800px"
          :footer="null"
      >
        <a-descriptions bordered :column="2" v-if="currentDetail">
          <a-descriptions-item label="姓名">{{ currentDetail.name }}</a-descriptions-item>
          <a-descriptions-item label="工号">{{ currentDetail.employeeId }}</a-descriptions-item>
          <a-descriptions-item label="部门">{{ currentDetail.department }}</a-descriptions-item>
          <a-descriptions-item label="职位">{{ currentDetail.position }}</a-descriptions-item>
          <a-descriptions-item label="发放月份">{{ currentDetail.month }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="currentDetail.status === 1 ? 'green' : 'orange'">
              {{ currentDetail.status === 1 ? '已发放' : '待发放' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="基本工资">¥{{ currentDetail.baseSalary }}</a-descriptions-item>
          <a-descriptions-item label="奖金">¥{{ currentDetail.bonus }}</a-descriptions-item>
          <a-descriptions-item label="津贴">¥{{ currentDetail.allowance || 0 }}</a-descriptions-item>
          <a-descriptions-item label="社保公积金">¥{{ currentDetail.insurance }}</a-descriptions-item>
          <a-descriptions-item label="个人所得税">¥{{ currentDetail.tax }}</a-descriptions-item>
          <a-descriptions-item label="实发工资" :span="2">
            <span style="font-weight: bold; color: #1890ff;">¥{{ currentDetail.actualSalary }}</span>
          </a-descriptions-item>
          <a-descriptions-item label="出勤天数">{{ currentDetail.attendanceDays }}天</a-descriptions-item>
          <a-descriptions-item label="请假天数">{{ currentDetail.leaveDays }}天</a-descriptions-item>
          <a-descriptions-item label="加班时长">{{ currentDetail.overtimeHours }}小时</a-descriptions-item>
        </a-descriptions>
      </a-modal>

      <!-- 编辑薪资模态框 -->
      <a-modal
          v-model:visible="editModalVisible"
          title="编辑薪资信息"
          @ok="handleEditSubmit"
          @cancel="editModalVisible = false"
      >
        <a-form :model="editFormState" :label-col="{ span: 6 }">
          <a-form-item label="基本工资" required>
            <a-input-number
                v-model:value="editFormState.baseSalary"
                :min="0"
                :step="100"
                style="width: 100%"
                addon-before="¥"
            />
          </a-form-item>
          <a-form-item label="奖金">
            <a-input-number
                v-model:value="editFormState.bonus"
                :min="0"
                :step="100"
                style="width: 100%"
                addon-before="¥"
            />
          </a-form-item>
          <a-form-item label="津贴">
            <a-input-number
                v-model:value="editFormState.allowance"
                :min="0"
                :step="100"
                style="width: 100%"
                addon-before="¥"
            />
          </a-form-item>
          <a-form-item label="社保公积金">
            <a-input-number
                v-model:value="editFormState.insurance"
                :min="0"
                :step="100"
                style="width: 100%"
                addon-before="¥"
            />
          </a-form-item>
          <a-form-item label="个人所得税">
            <a-input-number
                v-model:value="editFormState.tax"
                :min="0"
                :step="50"
                style="width: 100%"
                addon-before="¥"
            />
          </a-form-item>
          <a-form-item label="备注">
            <a-textarea v-model:value="editFormState.remark" :rows="3" />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<style scoped>
.salary-container {
  padding: 20px;
}

.stat-card {
  text-align: center;
}

.stat-card h2 {
  font-size: 24px;
  margin-bottom: 8px;
}

.stat-card p {
  margin: 0;
  color: #999;
}

.increase {
  color: #52c41a;
}

.decrease {
  color: #f5222d;
}

.statistics-container {
  margin-top: 16px;
}

.ant-descriptions-item-label {
  font-weight: bold;
  width: 120px;
}
</style>